package cn.chengpengper.shortlink.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.core.strategy.keygen.SnowflakeShardingKeyGenerator;
import org.springframework.context.annotation.Configuration;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author huchengpeng
 * @version v1.0.0
 * @date 2023/9/3 21:13
 * @description SnowFlakeWorkId配置
 */
@Slf4j
@Configuration
public class SnowFlakeWorkerIdConfig {
    /**
     * 动态指定 Sharding-Jdbc 的雪花算法中的work.id属性
     * {@link SnowflakeShardingKeyGenerator#getWorkerId()}
     */
    static {
        try {
            InetAddress inetAddress = Inet4Address.getLocalHost();
            String hostAddress = inetAddress.getHostAddress();
            String workerId = String.valueOf(Math.abs(hostAddress.hashCode()) % 1024);
            System.setProperty("workerId", workerId);
            log.info("SnowFlakeWorkerIdConfig get workerId:{}", workerId);
        } catch (UnknownHostException e) {
            log.error("SnowFlakeWorkerIdConfig getLocalHost has a exception:", e);
        }
    }
}
